import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.Arrays;

/**
 * 寻找每一对所有的共同好友
 * Input:
 * 100 500,600
 * 300 500,
 * Output:
 * [500,600] [100]
 */
public class FriendsGroup {
    public static class FriendsGroupMapper
            extends Mapper<Object, Text, Text, Text> {
        Text KeyOut = new Text();
        Text ValueOut = new Text();

        @Override
        protected void map(Object key, Text value, Context context)
                throws IOException, InterruptedException {
            String[] FriendPersons = value.toString().split("\t");
            String[] Persons = FriendPersons[1].split(",");
            Arrays.sort(Persons);
            ValueOut.set(FriendPersons[0]);
            for (int i = 0; i < Persons.length - 1; i++) {
                for (int j = i + 1; j < Persons.length; j++) {
                    KeyOut.set("[" + Persons[i] + "," + Persons[j] + "]");
                    context.write(KeyOut, ValueOut);
                }
            }
        }
    }

    public static class FriendsGroupReducer
            extends Reducer<Text, Text, Text, Text> {
        Text KeyOut = new Text();
        Text ValueOut = new Text();

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context)
                throws IOException, InterruptedException {
            StringBuilder Friends = new StringBuilder("[");
            for (Text value : values) {
                Friends.append(value.toString()).append(",");
            }
            KeyOut.set(key);
            ValueOut.set(Friends.substring(0, Friends.length() - 1) + "]");
            context.write(KeyOut, ValueOut);
        }
    }

    @SuppressWarnings("deprecation")
    public static boolean run(String in, String out)
            throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf, "CommonFriends");
        job.setJarByClass(FriendsGroup.class);
        job.setMapperClass(FriendsGroupMapper.class);
        job.setReducerClass(FriendsGroupReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.addInputPath(job, new Path(in));
        FileOutputFormat.setOutputPath(job, new Path(out));

        return job.waitForCompletion(true);
    }
}
